package com.nightsoul.retrofit.test.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;
import com.google.common.io.ByteStreams;
import com.google.gson.Gson;
import com.nightsoul.retrofit.test.pojo.User;
import com.nightsoul.retrofit.test.service.UserList;

@Controller
public class UserController {

	@RequestMapping("/users/list")
	public void listUsers(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		List<User> users = UserList.users;
		resp.setContentType("text/html; charset=UTF-8");
		Gson gson = new Gson();
		resp.getWriter().write(gson.toJson(users));
	}

	@RequestMapping("/group/{id}/users")
	public void groupList(HttpServletRequest req, HttpServletResponse resp, @PathVariable("id")Integer id)	throws ServletException, IOException {
		List<User> users = Lists.newArrayList();
		for(User user : UserList.users) {
			if(user.getGroupId().equals(id)) {
				users.add(user);
			}
		}
		resp.setContentType("text/html; charset=UTF-8");
		Gson gson = new Gson();
		resp.getWriter().write(gson.toJson(users));
	}

	@RequestMapping("users/new")
	public void createUser(HttpServletRequest req, HttpServletResponse resp)	throws ServletException, IOException {
		byte[] bytes = ByteStreams.toByteArray(req.getInputStream());
		resp.setContentType("text/html; charset=UTF-8");
		Gson gson = new Gson();
		User user = gson.fromJson(new String(bytes), User.class);
		System.out.println(user + " created");
		UserList.users.add(user);
		resp.getWriter().write(gson.toJson(user));
	}

	@RequestMapping("user/edit")
	public void updateUser(HttpServletRequest req, HttpServletResponse resp, User user)	throws ServletException, IOException {
		Gson gson = new Gson();
		for(User current : UserList.users) {
			if(current.getId().equals(user.getId())) {
				current.setName(user.getName());
				current.setPassword(user.getPassword());
			}
		}
		resp.getWriter().write(gson.toJson(user));
	}

	@RequestMapping("user/photo")
	public void updateUserPhoto(HttpServletRequest req, HttpServletResponse resp, MultipartFile photo)	throws ServletException, IOException {
		System.out.println(req.getParameter("description"));
		System.out.println(photo.getOriginalFilename() + ", " + photo.getSize());
		Gson gson = new Gson();
		resp.getWriter().write(gson.toJson(UserList.users.get(0)));
	}

}
